package thread;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 09 - 12
 * Time: 21:05
 */
//实现阻塞队列案例
class MyBlockingQueue {
    private String[] data = new String[1000];
    private volatile int size;
    private volatile int tail;
    private volatile int head;
    public void put(String elem) throws InterruptedException {
        synchronized (this) {
            while (size == data.length) {
                this.wait();
            }
            data[tail] = elem;
            tail++;
            if(tail == data.length) {
                tail = 0;
            }
            size++;
            this.notify();
        }
    }
    public String take() throws InterruptedException {
        synchronized (this) {
            while (size == 0) {
                this.wait();
            }
            String ret = data[head];
            head++;
            if (head == data.length) {
                head = 0;
            }
            size--;
            this.notify();
            return ret;
        }
    }
}
public class Demo7 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue();
        Thread t1 = new Thread(() -> {
            while (true) {
                try {
                    String result = queue.take();
                    System.out.println("消费模式：" + result);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread t2 = new Thread(() -> {
            int num = 1;
            while (true) {
                try {
                    queue.put(num + "");
                    System.out.println("生产模式：" + num);
                    num++;
                    //Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
    }
}
